<?php

namespace zhtfrontend\controllers;

use common\components\extenders\AjaxObject;

use common\components\helpers\Fun;
use common\components\services\customer\Account;
use common\components\services\message\ManualWechatMessage;
use common\models\datas\AccountRecord;
use common\models\datas\Customer;
use common\models\datas\CustomerBranchaccount;
use common\models\datas\CustomerDues;
use common\models\datas\DepositLog;
use common\models\datas\LoginAuth;
use common\models\datas\Setting;
use common\models\datas\Student;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Message\News;
use zhtfrontend\components\helpers\Funs;
use zhtfrontend\models\datas\ClassLesson;
use zhtfrontend\models\datas\ClassManage;
use zhtfrontend\models\datas\ClassStudent;
use zhtfrontend\models\datas\OrdersItems;
use zhtfrontend\models\datas\StudentCheck;
use yii\helpers\Html;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\data\Pagination;
use yii\helpers\Json;
use yii\web\BadRequestHttpException;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use common\components\helpers\Tree;
use moonland\phpexcel\Excel;

class DepositController extends \zhtfrontend\components\bases\BaseController
{
    public function actionIndex()
    {
        $param['searchData'] = \Yii::$app->request->get();
        $pageSize = isset($param['pageSize']) ? $param['pageSize'] : 12;
        $data = DepositLog::find()->where(['site_id' => Fun::getSiteId()])->orderBy('processing_time DESC');
        $dataSum = DepositLog::find()->where(['site_id' => Fun::getSiteId()]);
        $applySum = DepositLog::find()->where(['site_id' => Fun::getSiteId()]);
        if (!empty($param['searchData'])) {
            $search_data = $param['searchData'];
            if (!empty($search_data['year']) && !empty($search_data['mouth'])) {
                if ($search_data['types'] == 2) {
                    $time = $search_data['year'] . "-" . $search_data['mouth'];
                    $end = Fun::getCurMonthLastDay($time);
                    $data->andWhere(['<=', 'created_at', $end]);
                    $dataSum->andWhere(['<=', 'created_at', $end]);
                    $applySum->andWhere(['<=', 'created_at', $end]);
                } else {
                    $time = $search_data['year'] . "-" . $search_data['mouth'];
                    $start = Fun::getCurMonthFirstDay($time);
                    $end = Fun::getCurMonthLastDay($time);
                    $data->andWhere(['between', 'created_at', $start, $end]);
                    $dataSum->andWhere(['<=', 'created_at', $end]);
                    $applySum->andWhere(['<=', 'created_at', $end]);
                }
            }
            if (!empty($search_data['tel'])) {
                $customer_ids = Customer::find()->select('id')->where(['like', 'mobile', $search_data['tel']])->andWhere(['site_id' => Fun::getSiteId()])->column();
                $data->andWhere(['customer_id' => $customer_ids]);
                $dataSum->andWhere(['customer_id' => $customer_ids]);
                $applySum->andWhere(['customer_id' => $customer_ids]);
            }
            if (!empty($search_data['name'])) {
                $customer_ids = Customer::find()->select('id')->where(['like', 'name', $search_data['name']])->andWhere(['site_id' => Fun::getSiteId()])->column();
                $data->andWhere(['customer_id' => $customer_ids]);
                $dataSum->andWhere(['customer_id' => $customer_ids]);
                $applySum->andWhere(['customer_id' => $customer_ids]);
            }
            if (!empty($search_data['card_id'])) {
                $customer_ids = Customer::find()->select('id')->where(['like', 'card_id', $search_data['card_id']])->andWhere(['site_id' => Fun::getSiteId()])->column();
                $data->andWhere(['customer_id' => $customer_ids]);
                $dataSum->andWhere(['customer_id' => $customer_ids]);
                $applySum->andWhere(['customer_id' => $customer_ids]);
            }
            if (isset($search_data['status']) && $search_data['status'] != null) {
                $data->andWhere(['status' => $search_data['status']]);
                $dataSum->andWhere(['status' => $search_data['status']]);
                $applySum->andWhere(['status' => $search_data['status']]);
            }
            if (isset($search_data['processing_status']) && $search_data['processing_status'] != null) {
                $data->andWhere(['processing_status' => $search_data['processing_status']]);
                $dataSum->andWhere(['processing_status' => $search_data['processing_status']]);
                $applySum->andWhere(['processing_status' => $search_data['processing_status']]);
            }
        }
        $totals = 0;
        $totalsc = $dataSum->sum('money');
        if ($totalsc != null) {
            $totals = $totalsc;
        }
        $yesbacktotals = 0;
        $yesbacktotalsc = $dataSum->sum('actual_money');
        if ($yesbacktotalsc != null) {
            $yesbacktotals = $yesbacktotalsc;
        }
        $notbacktotals = $totals - $yesbacktotals;
        $renewtotals = 0;
        $renewtotalsc = $dataSum->andWhere(['status' => 2, 'processing_status' => 0])->sum('money');
        if ($renewtotalsc != null) {
            $renewtotals = $renewtotalsc;
        }
        $applyingtotalsc = $applySum->andWhere(['status' => 0, 'processing_status' => 1])->sum('money');
        if ($applyingtotalsc == null) {
            $applyingtotalsc = 0;
        }

        $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => $pageSize]);
        isset($param['page']) ? $pages->page = $param['page'] - 1 : 0;
        $model = $data->offset($pages->offset)->limit($pages->limit)->all();
        $array = Fun::asArray($model, ['customer_name', 'status_name', 'pay_type_name', 'items_name', 'operate', 'processing_name']);
        $content = "<h4 class='yx-total1 yx-floatl'>交款总金额：<span class='yx-color2cb4f3 yx-font16 yx-mr5'>{$totals}</span>元</h4><h4 class='yx-total1 yx-floatl'>未退总金额：<span class='yx-color2cb4f3 yx-font16 yx-mr5'>{$notbacktotals}</span>元</h4><h4 class='yx-total1 yx-floatl '>申请中：<span class='yx-color2cb4f3 yx-font16 yx-mr5'>{$applyingtotalsc} </span>元</h4><h4 class='yx-total1 yx-floatl '>已退总金额：<span class='yx-color2cb4f3 yx-font16 yx-mr5'>{$yesbacktotals} </span>元</h4><h4 class='yx-total1 yx-floatl'>转学费总金额：<span class='yx-color2cb4f3 yx-font16 yx-mr5'>{$renewtotals}</span>元</h4><div class='yx-clear'></div>";

        return $this->render('index', ['data' => $array, 'pages' => $pages, 'content' => $content]);
    }

    /*
     * 申请退款
     */
    public function actionApply()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        if ($id == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model = DepositLog::findOne($id);
        if ($model == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
            $model->processing_status = 1;
            $model->application_time = time();
            if ($model->save(false)) {
                return $this->redirectMessage('申请成功', Fun::url(['deposit/index']));
            } else {
                return $this->redirectMessage('申请失败', Fun::url(['deposit/index']));
            }

        }
        return $this->render('apply', ['model' => $model]);
    }

    public function actionView()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        if ($id == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model = DepositLog::findOne($id);
        if ($model == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        return $this->render('view', ['model' => $model]);
    }

    public function actionHandle()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        if ($id == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model = DepositLog::findOne($id);
        if ($model == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $status_arr = [];
        if ($model->processing_status == 1) {
            $status_arr = [
                3 => '通过',
                4 => '失败',
                5 => '转学费',
                0 => '退回申请',
            ];
        }
        $model->scenario = 'handle';
        $ClassS = [];
        $student = Student::find()->where(['customer_id' => $model->customer_id])->one();
        $classstudent = ClassStudent::find()->where(['student_id' => $student->id, 'order_sales_id' => $model->orders_items_id])->one();
        if (isset($classstudent->ordersitems)) {
            $okcount = StudentCheck::find()->where(['class_student_id' => $classstudent->id, 'status' => 1])->count();
            $goodsAttr = Funs::getGoodsAttr($classstudent->ordersitems->goods_id);
            $ClassS['name'] = $classstudent->ordersitems->name;
            $ClassS['class_count'] = isset($goodsAttr['class_count']) ? $goodsAttr['class_count'] : 0;
            $ClassS['ok_count'] = $okcount;
            $ClassS['status'] = $classstudent->status;
            $ClassS['order_sn'] = isset($classstudent->ordersitems->orders) ? $classstudent->ordersitems->orders->sn : '';
            $ClassS['scholarship_money'] = $classstudent->ordersitems->actual_scholarship_money;
        }

        //保证金付给
        $model->actual_money = 200;

        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
            if ($model->processing_status == 5 && $model->actual_money > 0) {
                $returnno = date('YmdHis') . $model->id;
                $model->status = 2;
                $model->processing_time = time();
                $model->operator_id = \Yii::$app->user->id;
                $model->operator_name = \Yii::$app->user->identity->name;
                $model->refund_no = $returnno;
                if ($model->save(false)) {
                    //账户资金
                    $customer_branchaccount = CustomerBranchaccount::findOne(['customer_id' => $model->customer_id]);
                    $customer_branchaccount->cash = $customer_branchaccount->cash + $model->money;
                    $customer_branchaccount->save(false);
                    //流水
                    $account = new AccountRecord();
                    $account->customer_id = $model->customer_id;
                    $account->site_id = Fun::getSiteId();
                    $account->cash = $model->money;
                    $account->state = 0;
                    $account->order_id = $model->orders_id;
                    $account->note = '保证金转学费';
                    $account->created_at = time();
                    $account->user_id = \Yii::$app->user->id;
                    $account->save(false);
                    Account::addRecharge($model->customer_id, $model->money);
                    return $this->redirectMessage('退款成功', Fun::url(['deposit/index']));
                }
            }
            $option = [
                'customer_id' => $model->customer_id,
                'deposit' => $model->money,
                'orders_id' => $model->orders_id,
                'note' => '用户退保证金',
                'state' => 4
            ];
            if ($model->processing_status == 3 && $model->actual_money > 0) {
                if ($model->pay_type == 2) {
                    $returnno = date('YmdHis') . $model->id;
                    $model->status = 1;
                    $model->processing_time = time();
                    $model->operator_id = \Yii::$app->user->id;
                    $model->operator_name = \Yii::$app->user->identity->name;
                    $model->refund_no = $returnno;
                    $model->save(false);
                    Account::CustomerAccountReduce($option);
                    return $this->redirectMessage('退款成功', Fun::url(['deposit/index']));
                } else {
                    return $this->redirectMessage('退款失败', Fun::url(['deposit/index']));
                }
            }
        }
        return $this->render('handle', ['model' => $model, 'class' => $ClassS, 'status_arr' => $status_arr]);
    }


//查看课次详情
    public
    function actionClassdetails()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        if ($id == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model = DepositLog::findOne($id);
        if ($model == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $student = Student::find()->where(['customer_id' => $model->customer_id])->one();
        $checkList = StudentCheck::find()->where(['student_id' => $student->id, 'order_sales_id' => $model->orders_items_id])->all();
        if ($checkList == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '此学生未开班时退课，退还保证金'));
        }

        $data = [];
        $i = 0;
        foreach ($checkList as $val) {
            $data[$i]['name'] = isset($val->classlesson) ? $val->classlesson->title : '';
            $data[$i]['lesson'] = isset($val->classlesson) ? $val->classlesson->lesson : '';
            $data[$i]['student_name'] = isset($val->student) ? $val->student->name : '';
            if ($val->status == 0) {
                $status = '旷课';
            } elseif ($val->status == 1) {
                $status = '已上课';
            } elseif ($val->status == 2) {
                $status = '已请假';
            } elseif ($val->status == 3) {
                $status = '已退课';
            }

            $data[$i]['status'] = $status;
            $i++;
        }

        return $this->render('classdetails', ['model' => $model, 'data' => $data]);
    }

//查看退款
    public
    function actionSee()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        if ($id == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model = DepositLog::findOne($id);
        if ($model == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        if ($model->processing_status != 3 && $model->pay_type != 1) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '为退款或不是微信支付'));
        }

        $options = \Yii::$app->params['options'];
        $app = new Application($options);
        $payment = $app->payment;
        if (!empty($model->refund_no)) {
            $result = $payment->queryRefundByRefundNo($model->refund_no);
        } else {
            $result = $payment->queryRefundByTransactionId($model->transaction_id);
        }
        return $this->render('see', ['result' => $result]);
    }


}